package com.example.distributionlock;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.example.demo.DemoApplication;

@SpringBootTest(classes = DemoApplication.class)
public class LockServiceTest {
    @Autowired
    private LockService service;

    private int count = 0;
    @Test
    public void test() throws Exception {
        List<CompletableFuture<Void>> taskList = new ArrayList<>();
        for (int threadIndex = 0; threadIndex < 10; threadIndex++) {
            CompletableFuture<Void> task = CompletableFuture.runAsync(() -> addCount());
            taskList.add(task);
        }
        CompletableFuture.allOf(taskList.toArray(new CompletableFuture[0])).join();
    }

    public void addCount() {
        String id = UUID.randomUUID().toString().replace("-", "");

        boolean tryLock = service.lock("account", id);
        while (tryLock == false) {
            tryLock = service.lock("account", id);
        }

        for (int i = 0; i < 10_000; i++) {
            count++;
        }

        try {
            Thread.sleep(100_000);
        } catch (Exception e) {
            System.out.println(e);
        }

        boolean releaseLock = service.unlock("account", id);

    }
}
